import request from '@/utils/request'

// 数据转换函数：将后端Precords实体转换为前端组件需要的数据格式
function transformPrecordsToFrontendData(precordsList) {
  return precordsList.map(record => {
    // 计算停车时长
    let parkingDuration = ''
    if (record.entertime && record.outtime) {
      const enterTime = new Date(record.entertime)
      const exitTime = new Date(record.outtime)
      const durationMs = exitTime - enterTime
      const hours = Math.floor(durationMs / (1000 * 60 * 60))
      const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60))
      parkingDuration = `${hours}小时${minutes}分钟`
    } else if (record.entertime) {
      const enterTime = new Date(record.entertime)
      const now = new Date()
      const durationMs = now - enterTime
      const hours = Math.floor(durationMs / (1000 * 60 * 60))
      const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60))
      parkingDuration = `${hours}小时${minutes}分钟`
    }

    return {
      id: record.pid,
      carNumber: record.license, // 后端使用license，前端使用carNumber
      entryTime: record.entertime, // 后端使用entertime，前端使用entryTime
      exitTime: record.outtime, // 后端使用outtime，前端使用exitTime
      parkingDuration: parkingDuration, // 计算停车时长
      amount: record.payment || 0, // 后端使用payment，前端使用amount
      paymentStatus: record.ispay === 1 ? '已缴费' : '未缴费', // 后端使用ispay，前端使用paymentStatus
      cartype: record.cartype,
      garagenum: record.garagenum
    }
  })
}

// 查询车辆信息列表
export function listPrecords(query) {
  return request({
    url: '/system/precords/list',
    method: 'get',
    params: query
  }).then(response => {
    // 转换数据格式后返回
    if (response.rows) {
      response.rows = transformPrecordsToFrontendData(response.rows)
    }
    return response
  })
}

// 查询车辆信息详细
export function getPrecords(pid) {
  return request({
    url: '/system/precords/' + pid,
    method: 'get'
  }).then(response => {
    // 如果是单个记录，也进行转换
    if (response.data) {
      const transformed = transformPrecordsToFrontendData([response.data])[0]
      response.data = transformed
    }
    return response
  })
}

// 新增车辆信息
export function addPrecords(data) {
  return request({
    url: '/system/precords',
    method: 'post',
    data: data
  })
}

// 修改车辆信息
export function updatePrecords(data) {
  return request({
    url: '/system/precords',
    method: 'put',
    data: data
  })
}

// 删除车辆信息
export function delPrecords(pid) {
  return request({
    url: '/system/precords/' + pid,
    method: 'delete'
  })
}
